import { Avatar, Button, Popover } from "antd"
import { useDispatch, useSelector } from "react-redux"
import { ROOT_STATE } from "../../store"
import style from "./index.module.css"
import { changeLoginState, clearUser } from "../../store/userSlice"
type Props = {
  open: () => void
}
export const LoginAvatar = ({ open }: Props) => {
  const { isLogin, userInfo } = useSelector(
    (state: ROOT_STATE) => state.userReducer
  )
  const dispatch = useDispatch()
  const logOut = () => {
    // 退出登录
    // 清空本地storage
    localStorage.removeItem("token")
    // 清空store
    dispatch(changeLoginState(false))
    dispatch(clearUser())
  }
  let content: JSX.Element
  if (isLogin) {
    content = (
      <Popover
        content={<Button onClick={logOut}>退出</Button>}
        placement="bottom"
      >
        <div className={style.wraper}>
          <Avatar
            size={64}
            src={import.meta.env.VITE_APP_BASE_SERVICE + userInfo.avatar}
          />
        </div>
      </Popover>
    )
  } else {
    content = (
      <Button type="primary" onClick={open}>
        注册/登录
      </Button>
    )
  }
  return <>{content}</>
}
